import os.path
import sys
import datetime
from PIL import Image

"""
功能：将jpg图片取模，图片二进制数据直接转换为hex头文件，用于TJpg_Decoder
"""


# 读图片二进制数据，转换为16进制格式
def read_jpg_file(file_path):
    hex_list = []
    with open(file_path, "rb") as file:
        data = file.read()
        print(data)
        for i in range(len(data)):
            hex_list.append(f"0x{data[i]:02X}")
    return hex_list


# 生成头文件
def write_c_header_file(file_name, img, hex):
    name = os.path.splitext(file_name)[0]
    now = datetime.datetime.now()
    time = now.strftime("%Y-%m-%d %H:%M:%S")
    with open(f"{name}.h", "w") as f:
        f.writelines("// Generated by  : ConvertTJpg v1.0\n")
        f.writelines("// Generated from: {}\n".format(file_name))
        f.writelines("// Time generated: {}\n".format(time))
        f.writelines("// Dimensions    : {}x{} pixels\n".format(img.width, img.height))
        f.writelines("// Size          : {} Bytes\n".format(len(hex)))
        f.writelines("\n")
        f.writelines("#include <pgmspace.h>\n")
        f.writelines("\n")
        f.writelines("const uint8_t img{}[] PROGMEM ={{\n".format(name))
        count = 0
        for i in range(len(hex)):
            count = count + 1
            f.write(hex[i])
            f.write(', ')
            if count == 16:
                count = 0
                f.write('\n')
        f.writelines("\n};")


# 测试
# image = Image.open("loading4.jpg")
# data = read_jpg_file("loading4.jpg")
# print(data)
# write_c_header_file("loading4.jpg", image, data)

if __name__ == '__main__':
    print(sys.argv)
    if len(sys.argv) < 2:
        print("用法: 把要转换的 JPG/PNG/BMP 文件拖到.exe图标上即可")
        exit(0)

    for i, img_path in enumerate(sys.argv[1:]):
        fileName = os.path.basename(img_path)
        print("正在转换图片[{}] ...".format(fileName))
        img = Image.open(img_path)
        # 先转RGB，避免报错：cannot write mode P as JPEG
        imgRGB = img.convert('RGB')
        # 转换为jpg格式
        tmp_file = "ConvertTJpg_temp_1q2w3e4r.jpg"
        imgRGB.save(tmp_file)
        # 读取jpg图片数据
        hex = read_jpg_file(tmp_file)
        # 删除临时文件
        os.remove(tmp_file)
        # 生成头文件
        write_c_header_file(fileName, img, hex)
